﻿using System;
using System.Windows.Forms;
using ActivitiesControl.Domain.Model;
using ActivitiesControl.GUI.Desktop.Forms;
using ActivitiesControl.Domain.Utils;

namespace ActivitiesControl.GUI.Desktop
{
	public class Context
		: ApplicationContext
	{
		private ActivitiesForm activities;
		private AuthenticationForm authentication;

		private Context()
		{
			ServicesLocator.ActivityServices.MessageRaised += new MessageHandler(Services_MessageRaised);
			ServicesLocator.ProjectServices.MessageRaised += new MessageHandler(Services_MessageRaised);
			ServicesLocator.ResourceServices.MessageRaised += new MessageHandler(Services_MessageRaised);
			ServicesLocator.UserServices.MessageRaised += new MessageHandler(Services_MessageRaised);

			authentication = new AuthenticationForm();
			authentication.Authenticated += new Action<User>(authentication_Authenticated);
			authentication.FormClosed += new FormClosedEventHandler(authentication_FormClosed);
			authentication.Show();
		}

		void messages_FormClosing(object sender, FormClosingEventArgs e)
		{
			e.Cancel = true;
			((Form)sender).Hide();
		}

		void Services_MessageRaised(object sender, MessageEventArgs e)
		{
			if (activities != null)
				activities.AppendText(e.Message.Text);
		}

		void authentication_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (e.CloseReason == CloseReason.UserClosing)
				form_FormClosed(sender, e);
		}

		void authentication_Authenticated(User obj)
		{
			activities = new ActivitiesForm(obj);
			activities.FormClosed += new FormClosedEventHandler(form_FormClosed);
			activities.Show();
			authentication.Dispose();
		}

		void form_FormClosed(object sender, FormClosedEventArgs e)
		{
			ExitThread();
			Dispose(true);
		}

		private static volatile Context instance;
		private static object syncRoot = new object();

		public static Context Instance
		{
			get
			{
				if (instance == null)
				{
					lock (syncRoot)
					{
						if (instance == null)
							instance = new Context();
					}
				}
				return instance;
			}
		}
	}
}
